package indexes;

import java.io.IOException;
import java.util.List;

import trees.AVLTree;
import util.PlayerLogger;
/**
 * A PlayerNameIndex contains the relationships between a player name
 * and the location of their records within the database file.
 * @author bfults (Brian Fults - 905084698)
 *
 */
public class PlayerNameIndex
{

    private AVLTree<PlayerName> index;
    
    /**
     * Default constructor.  Indexes use a logger to
     * record the structure.
     * @param logger
     */
    public PlayerNameIndex(PlayerLogger logger)
    {
        index = new AVLTree<PlayerName>(logger);
    }
    /**
     * Adds the offset with its key to the index.  If the 
     * key already exists, the tree takes care of it by adding
     * the offset to a list of offsets for that key.
     * @param key
     * @param value
     * @throws IOException 
     */
    public void add( String key, Long value ) throws IOException
    {
        PlayerName found = index.silentFind(new PlayerName(key, null));
        if (found != null)
        {
            found.getRecords().add(value);
        }
        else
        {
            index.insert(new PlayerName(key, value));
        }
    }


    /**
     * A player name may have several offsets, so we give back
     * a list of offsets for the given player.
     * @param key Player name to search for
     * @return Null if the player name is not found, a list
     * of file offsets otherwise.
     * @throws IOException 
     */
    public List<Long> get( String key ) throws IOException
    {
        PlayerName result = index.find(new PlayerName(key, null));
        return result != null ? result.getRecords() : null;
    }

    /**
     * In this case, the keys are not unique, so we require
     * that the caller knows which value should be removed as well.
     * The tree already accounts for this.
     * @param playerName
     * @throws IOException 
     * @throws IOException 
     */
    public void remove( PlayerName playerName ) throws IOException
    {
        PlayerName found = index.find(playerName);
        if (found != null)
        {
            if (found.getRecords().contains(playerName.getRecord())) //if the player to remove is in the list
            {
                found.getRecords().remove(playerName.getRecord());
                if (found.getRecords().isEmpty())
                {
                    index.remove(playerName);
                }
            }
        }
    }
    
    /**
     * Writes a representation of the index to the log
     * file.
     * @throws IOException
     */
    public void logIndex() throws IOException
    {
        index.logTree();
    }

}
